package com.company.woye.songbuState;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.company.woye.MyApplication;
import com.company.woye.QueryCutPlanActivity;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.internet.KjjPHCallBack;
import com.company.woye.onpackage.entity.BestOnPackageEntity;
import com.company.woye.utils.SharedPreferenceUtils;
import com.company.woye.utils.Toaster;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.company.woye.utils.BaseRequest.postJsonData;

public class SongbuStateActivity extends BaseActivity {


    @BindView(R.id.iv_checkout_console_back)
    TextView ivCheckoutConsoleBack;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.tv_have_no_call)
    TextView tvHaveNoCall;
    @BindView(R.id.tv_have_call)
    TextView tvHaveCall;
    @BindView(R.id.tv_cll_agv)
    TextView tvCllAgv;
    @BindView(R.id.tv_hand_search)
    TextView tvHandSearch;
    @BindView(R.id.tv_songbu_rock)
    TextView tvSongbuRock;
    @BindView(R.id.tv_curren_state)
    TextView tvCurrenState;
    @BindView(R.id.tv_match_num)
    TextView tvMatchNum;
    @BindView(R.id.tv_already_song)
    TextView tvAlreadySong;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_let_state)
    TextView tvLetState;
    @BindView(R.id.tv_right_station)
    TextView tvRightStation;
    @BindView(R.id.tv_right_state)
    TextView tvRightState;
    @BindView(R.id.lv_detail)
    ListView lvDetail;
    @BindView(R.id.tv_plan_query)
    TextView tvPlanQuery;
    @BindView(R.id.tv_songbu_gongwei)
    TextView tvSongbuGongwei;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.rb_left)
    RadioButton rbLeft;
    @BindView(R.id.rb_right)
    RadioButton rbRight;
    @BindView(R.id.rg_checkout)
    RadioGroup rgCheckout;
    private URI webUrl;
    private String TAG = getClass().getSimpleName();
    private final static int MSG_CallAgvResult = 9003;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //重连
            if (msg.what == 102) {
                if (webSocketClient != null) {
                    Log.e(TAG, "重连");
                    webSocketClient.connect();
                }
            }
            //刷新数据
            if (msg.what == 101) {
                Log.e(TAG, "获取数据");
                getData();
            }
            if (msg.what == MSG_CallAgvResult) {
                System.out.println(msg.obj);
                System.out.println(msg.arg1);
                try {
                    JSONObject result = new JSONObject(String.valueOf(msg.obj));
                    if (result.has("status") && result.has("errorinfo")) {
                        if (result.getInt("status") == 0) {
                            Toaster.showLong(SongbuStateActivity.this,result.getString("errorinfo"));
                        } else {
                            AlertDialog alertDialog = new AlertDialog.Builder(SongbuStateActivity.this)
                                    .setTitle("提示").setMessage(result.getString("errorinfo"))
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            return;
                                        }
                                    }).create();
                            alertDialog.show(); // 显示对话框
                        }
                    } else {
                        AlertDialog alertDialog = new AlertDialog.Builder(SongbuStateActivity.this)
                                .setTitle("提示").setMessage(msg.obj.toString())
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                    }
                } catch (JSONException e) {
                    //e.printStackTrace();
                    Toaster.showLong(SongbuStateActivity.this,"处理失败");
                }
            }
            return true;
        }
    });
    private WebSocketClient webSocketClient;

    boolean isHandleDis = false;
    String FormType = getClass().getSimpleName();
    String stationNo = "", songbuStation = "";

    private SongbuStateAdapter adapter;
    private List<RockBean.DataBean.RackDetailBean> list = new ArrayList<>();

    private void getData() {
        String url=MyApplication.UrlApi + "/api/web/songbuGetPlaceRackMx?placeNo=" + songbuStation;
        System.out.println(url);
        OkHttpUtils.post().url(url).build().execute(new KjjPHCallBack<RockBean>(RockBean.class, this, false) {
            @Override
            public void myError(Call call, Exception e, int id) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(RockBean response, int id) {
                Log.e(TAG, response.toString());
                if (response.getStatus() == 0) {
                    if (response.getData() != null) {
                        System.out.println("response:"+response);
                        if (response.getData().getRackInfo() != null && response.getData().getRackInfo().size() > 0) {
                            RockBean.DataBean.RackInfoBean rock = response.getData().getRackInfo().get(0);
                            if (rock != null) {
                                tvLeft.setText(rock.getLeftRackNo());
                                tvLetState.setText(rock.getLeftInfo());
                                tvRightStation.setText(rock.getRightRackNo());
                                tvRightState.setText(rock.getRightInfo());

                                tvSongbuRock.setText(rock.getLooseRackNo());
                                tvAlreadySong.setText(rock.getReadyPiece() + "");
                                tvCurrenState.setText(rock.getRackNo());
                                tvMatchNum.setText(rock.getTotalPiece() + "");
                            }
                        }
                        if (response.getData().getRackDetail() != null && response.getData().getRackDetail().size() > 0) {
                            list.clear();
                            list.addAll(response.getData().getRackDetail());
                            adapter.notifyDataSetChanged();
                        }
                    }

                } else {
                    Toast.makeText(SongbuStateActivity.this, response.getErrorinfo(), Toast.LENGTH_LONG).show();
                }

            }
        });

    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_songbu_state;
    }

    @Override
    public void initView() {
        adapter = new SongbuStateAdapter(this, list);
        lvDetail.setAdapter(adapter);
        songbuStation = (String) SharedPreferenceUtils.getData(sharedPreferences, "songbuGongWei", "");
        tvSongbuGongwei.setText("松布工位:" + songbuStation);
        rbLeft.setText( (String) SharedPreferenceUtils.getData(sharedPreferences, "leftGongWei", ""));
        rbRight.setText( (String) SharedPreferenceUtils.getData(sharedPreferences, "rightGongWei", ""));
        String url = ((String) SharedPreferenceUtils.getData(sharedPreferences, "UrlApi", "")).replace("http", "ws");
        url = url + "/websocket/SongbuMonitor-" + songbuStation;
        Log.e(TAG, "url:" + url);
        webUrl = URI.create(url);
        webSocketClient = new WebSocketClient(webUrl) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                Log.e(TAG, "web---open");
            }

            @Override
            public void onMessage(String message) {
                Log.e(TAG, "web---message" + message);
                handler.sendEmptyMessage(101);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                Log.e(TAG, "web---onClose");

                if (webSocketClient != null && !webSocketClient.isConnecting() && !isHandleDis) {
                    handler.postDelayed(new Runnable() {
                        @RequiresApi(api = Build.VERSION_CODES.P)
                        @Override
                        public void run() {
                            Log.e(TAG, "web---onClose--重连");
                            webSocketClient = new WebSocketClient(webUrl) {
                                @Override
                                public void onOpen(ServerHandshake handshakedata) {

                                }

                                @Override
                                public void onMessage(String message) {
                                    Log.e(TAG, "web---message重连");
                                    handler.sendEmptyMessage(101);
                                }

                                @Override
                                public void onClose(int code, String reason, boolean remote) {

                                }

                                @Override
                                public void onError(Exception ex) {

                                }
                            };
                            handler.postDelayed(this::run, 102, 5000);
                        }
                    }, 1000);
                }
            }

            @Override
            public void onError(Exception ex) {
                Log.e(TAG, "web---ex" + ex.getMessage().toString());
            }
        };
        webSocketClient.connect();


        rgCheckout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb = (RadioButton) findViewById(group.getCheckedRadioButtonId());
                stationNo = rb.getText().toString();
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "connect state:" + webSocketClient.isClosing());
        if (webSocketClient != null && !webSocketClient.isClosing()) {
            isHandleDis = true;
            webSocketClient.close();
        }
        handler.removeCallbacksAndMessages(null);
    }


    @OnClick({R.id.tv_cll_agv, R.id.tv_hand_search, R.id.iv_checkout_console_back, R.id.tv_have_no_call, R.id.tv_have_call, R.id.tv_plan_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_checkout_console_back:
                finish();
                break;
            //拉走盘呼叫
            case R.id.tv_cll_agv:
                callAgv("", FormType, songbuStation, stationNo, "松布12h", "拉走空托盘呼叫");
                break;
            //无托盘呼叫
            case R.id.tv_have_no_call:
                callAgv("", FormType, songbuStation, stationNo, "松布12h", "无托盘呼叫");

                break;
            //有空托盘呼叫
            case R.id.tv_have_call:
                callAgv("", FormType, songbuStation, stationNo, "松布12h", "有空托盘呼叫");

                break;
            case R.id.tv_plan_query:
                Intent outIntent = new Intent(this, QueryCutPlanActivity.class);
                Bundle paramBundle = new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", MyApplication.curLoginUserNo);
                paramBundle.putString("LoginUser", MyApplication.curLoginUser);
                paramBundle.putString("CurDepartNo", MyApplication.DepartMentNo);
                paramBundle.putString("CurDepart", MyApplication.DepartMent);
                paramBundle.putString("QueryTitle", "拉布单查询");
                paramBundle.putString("QueryType", "CutPlan");
                paramBundle.putString("ManuDepart", "");
                paramBundle.putString("OrderNo", "");
                paramBundle.putString("StyleNo", "");
                paramBundle.putString("StyleSort", "");
                paramBundle.putString("NeedOrder", "NO");
                paramBundle.putString("NeedFilter", "YES");
                paramBundle.putString("FilterHint", "请输入拉布单号或缸号");
                outIntent.putExtras(paramBundle);
                startActivity(outIntent);
                break;
            //手动查询
            case R.id.tv_hand_search:
                getData();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    //呼叫AGV
    private void callAgv(String Barcode, String FormType, String StationNo, String PlaceNo, String RackType, String OperType) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("Barcode", Barcode);
            jsonObject.put("FormType", FormType);
            jsonObject.put("StationNo", StationNo);
            jsonObject.put("PlaceNo", PlaceNo);
            jsonObject.put("RackType", RackType);
            jsonObject.put("OperType", OperType);
            jsonObject.put("UserNo", MyApplication.curLoginUserNo);
            jsonObject.put("TaskID", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println(jsonObject.toString());
        postJsonData(MyApplication.UrlApi + "/api/GreyCloth/SongbuCallAgv", jsonObject.toString(), handler, MSG_CallAgvResult);

    }

}
